package com.auto.survey.activity.monitoring

import android.content.Intent
import android.util.Log
import android.view.View
import android.widget.TextView
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.auto.survey.R
import com.auto.survey.activity.bluetooth.BluetoolsActivity
import com.auto.survey.activity.bluetooth.BluetoothManagerUtil
import com.auto.survey.activity.monitoring.IntentKey.KEY_INTENT_OBJECT_ID
import com.auto.survey.activity.monitoring.IntentKey.KEY_INTENT_PROJET_ID
import com.auto.survey.activity.monitoring.IntentKey.KEY_INTENT_STATION_ID
import com.auto.survey.activity.monitoring.adapter.MontoringPointAdapter
import com.auto.survey.activity.monitoring.adapter.MontoringPointAdapter.OnPointClickItemListener
import com.auto.survey.activity.monitoring.ctrlmeasure.CtrlMeasureActivity
import com.auto.survey.activity.monitoring.dao.MonitoringRepository
import com.auto.survey.activity.monitoring.entity.MonitoringPoint
import com.auto.survey.activity.monitoring.entity.MonitoringStation
import com.auto.survey.activity.monitoring.modle.InitCollectionVeiwModle
import com.auto.survey.base.BaseActivity
import com.auto.survey.base.CustomApplication
import com.auto.survey.geocom.GeoComCommon
import com.auto.survey.geocom.GeoComHelper
import com.auto.survey.util.Helper
import com.auto.survey.widget.CentreToast
import com.auto.survey.widget.dialog.InfoDialog
import com.auto.survey.widget.dialog.loadingdialog.LoadingDialog
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlin.getValue

/**
 * 初始采集成果
 */
class InitCollectionActivity : BaseActivity() {

    private var projectId:Int = -1
    private var objectId:Int = -1
    private var stationId:Int = -1
    private var pointCount = 0
    private val database = MonitoringRepository()

    private lateinit var tv_station1:TextView
    private lateinit var tv_station2:TextView
    private var adapter: MontoringPointAdapter? = null

    private var stationBean: MonitoringStation?=null

    private val bluetoothManager by lazy { BluetoothManagerUtil.getInstance(this) }
    private val geoComHelper:GeoComHelper by lazy { GeoComHelper.getInstance(bluetoothManager) }

    private var isBluetoothConnected = false
    // 创建并显示加载框
    private var loadingDialog: LoadingDialog?= null

    private val viewModel: InitCollectionVeiwModle by viewModels()

    override fun initView() {


        projectId = intent.getIntExtra(KEY_INTENT_PROJET_ID, -1)
        objectId = intent.getIntExtra(KEY_INTENT_OBJECT_ID, -1)
        stationId = intent.getIntExtra(KEY_INTENT_STATION_ID, -1)

        mTopBar?.visibility = View.VISIBLE
        mTopBar?.setBackgroundResource(R.color.action_bar)

        mComment_title?.visibility = View.VISIBLE
        mComment_title?.setBackgroundResource(R.color.action_bar)
        mComment_title?.setTitle("初始采集成果")

        loadingDialog = LoadingDialog(this)
        tv_station1 = findViewById(R.id.tv_init_collection_station_measure1)
        tv_station2 = findViewById(R.id.tv_init_collection_station_measure2)

        lifecycleScope.launch {
            stationBean = database.getStationById(stationId)
            withContext(Dispatchers.Main) {
                if (stationBean != null) {
                    val rlt = "测站坐标：\n" +
                            "\u3000N:${Helper.formateDecimal(stationBean!!.stationX)}\n" +
                            "\u3000E:${Helper.formateDecimal(stationBean!!.stationY)}\n" +
                            "\u3000Z:${Helper.formateDecimal(stationBean!!.stationZ)}"
                    tv_station1.text = rlt
                }
            }

            viewModel.station.observe(this@InitCollectionActivity) {

                val eqSt_x = it[InitCollectionVeiwModle.STATION_X]
                val eqSt_y = it[InitCollectionVeiwModle.STATION_Y]
                val eqSt_z = it[InitCollectionVeiwModle.STATION_Z]
                val eqSt_h = it[InitCollectionVeiwModle.EQUMENT_H]

                val strEqSt = "仪器坐标：\n" +
                        "\u3000N:${Helper.formateDecimal(eqSt_x)}\n" +
                        "\u3000E:${Helper.formateDecimal(eqSt_y)}\n" +
                        "\u3000Z:${Helper.formateDecimal(eqSt_z)}\n"

                tv_station2.text = strEqSt
            }
        }

        onClick()

        registerBlueCallback()

        val recyview = findViewById<RecyclerView>(R.id.rv_init_collection)
        recyview.layoutManager = LinearLayoutManager(this)
        adapter = MontoringPointAdapter(true, recyview)
        adapter?.setOnItemClickListener(object: OnPointClickItemListener{
            override fun ontItemPointClick(point: MonitoringPoint, selectedPosition: Int) {
                Log.i("InitCollectionActivity", "=====ontItemPointClick======selectedPosition = $selectedPosition")

                if (!isBluetoothConnected) {
                        CentreToast.instance.show("请先连接仪器",false)
                    return
                }

                if(point.collected) {
                    loadingDialog?.show()
                    geoComHelper.startExecution(listOf(GeoComCommon.AUT_MakePositioning(point.pointHz.toString(), point.pointV.toString())))
                }

            }

        })
        recyview.adapter = adapter
    }

    private fun registerBlueCallback() {

        if (bluetoothManager.isBluetoothConnected()) {
            isBluetoothConnected = true
            geoComHelper.startExecution(listOf(GeoComCommon.TMC_GetStation))
        }

        geoComHelper.onConnectionStateChanged { device, state ->
            if (bluetoothManager.isBluetoothConnected()) {
                CentreToast.instance.show("设备连接成功", true)
                isBluetoothConnected = true
                //连接成功后，发送获取当前测站坐标命令
                geoComHelper.startExecution(listOf(GeoComCommon.TMC_GetStation))
            } else {
                isBluetoothConnected = false
            }
        }

        geoComHelper.resultCallback { results, params->
            results.forEach {
                Log.i("InitCollectionActivity", "name = ${it.name}, command=${it.command}, result=${it.result}")

                if (it.name == GeoComCommon.TMC_GetStation.name && CustomApplication.isAppInForeground) {
                    val list = Helper.parseJson(it.result)
                    if(list.isEmpty()){
                        return@resultCallback
                    }

                    val station_x = list[2]
                    val station_y = list[1]
                    val station_z = list[3]
                    val eqHeight = list[4]  //仪器高

                    Log.i("InitCollectionActivity", "station_x = $station_x, station_y=$station_y, station_z=$station_z， eqHeight = $eqHeight")
//
                    viewModel.notifyEqStation(station_x.toDouble(), station_y.toDouble(), station_z.toDouble(),  eqHeight.toDouble())
                }

                if (it.name == GeoComCommon.AUT_MakePositioning.name && CustomApplication.isAppInForeground) {
                    loadingDialog?.dismiss()
                }
            }

        }

        //如果蓝牙已经连接，直接注册回调。 发送命令。 未连接的情况下，延时一会，给service初始化的时间再注册

    }

    private fun onClick() {
        findViewById<TextView>(R.id.tv_init_collection_connectblue).setOnClickListener {
            val intent = Intent()
            intent.setClass(this@InitCollectionActivity, BluetoolsActivity::class.java)
            startActivity(intent)
        }

        findViewById<TextView>(R.id.tv_init_collection).setOnClickListener {
            if (!isBluetoothConnected) {
                CentreToast.instance.show("请先连接仪器", false)
                return@setOnClickListener
            }

            val intent = Intent()

            intent.putExtra(KEY_INTENT_PROJET_ID, projectId)
            intent.putExtra(KEY_INTENT_OBJECT_ID, objectId)
            intent.putExtra(KEY_INTENT_STATION_ID, stationId)

            intent.setClass(this@InitCollectionActivity, DoCollectedActivity::class.java)
            startActivity(intent)
        }

        findViewById<TextView>(R.id.tv_init_collection_autocheck).setOnClickListener {
            if (!isBluetoothConnected) {
                CentreToast.instance.show("请先连接仪器", false)
                return@setOnClickListener
            }


            val station_rlt = "仪器设站坐标：N${stationBean?.stationX}" +
                    "\n 仪器设站坐标：E${stationBean?.stationY} " +
                    "\n仪器设站坐标：Z${stationBean?.stationZ} " +
                    "\n仪器设高：${stationBean?.stationHeight} " +
                    "\n测站中共有测点：$pointCount"

            InfoDialog.Builder(this@InitCollectionActivity)
                .setTitle("基本信息")
                .setMessage(station_rlt)
                .setCancelable(true)
                .setOnCancelListener {  }
                .setOnConfirmListener {
                    val intent = Intent()
                    intent.putExtra(KEY_INTENT_PROJET_ID, projectId)
                    intent.putExtra(KEY_INTENT_OBJECT_ID, objectId)
                    intent.putExtra(KEY_INTENT_STATION_ID, stationId)
                    intent.setClass(this@InitCollectionActivity,AutoCheckActivity::class.java)
                    startActivity(intent)
                }
                .show()
        }

        findViewById<TextView>(R.id.tv_init_collection_applogize).setOnClickListener {
            val intent = Intent()
            intent.putExtra(KEY_INTENT_PROJET_ID, projectId)
            intent.putExtra(KEY_INTENT_OBJECT_ID, objectId)
            intent.putExtra(KEY_INTENT_STATION_ID, stationId)
            intent.setClass(this@InitCollectionActivity, AutoCheckHistoryActivity::class.java)
            startActivity(intent)
        }

        findViewById<TextView>(R.id.tv_init_collection_measure).setOnClickListener {
            val intent = Intent()
            intent.putExtra(KEY_INTENT_PROJET_ID, projectId)
            intent.putExtra(KEY_INTENT_OBJECT_ID, objectId)
            intent.putExtra(KEY_INTENT_STATION_ID, stationId)
            intent.setClass(this@InitCollectionActivity, CtrlMeasureActivity::class.java)
            startActivity(intent)
        }
    }

    override fun onResume() {
        super.onResume()
        lifecycleScope.launch {
            database.getMonitoringPointClloectedByStationId(stationId).collect{
                adapter?.setData(it)
            }
        }

        lifecycleScope.launch(Dispatchers.IO) {
            pointCount = database.getPointClloectedCountByStationId(stationId)
            Log.i("InitCollectionActivity", "pointCount = $pointCount")

        }

    }

    override fun onDestroy() {
        super.onDestroy()
        geoComHelper.removeResultCallback()
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_init_collection
    }
}